import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/dialog_helpers.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/common/widget/underline_text_field.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/login/application/notifier/login_apple_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_wechat_notifier.dart';
import 'package:casdon/modules/login/domain/states/login_apple_state.dart';
import 'package:casdon/modules/login/domain/states/login_pwd_state.dart';
import 'package:casdon/modules/login/domain/states/login_wechat_state.dart';
import 'package:casdon/modules/login/providers/login_apple_provider.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:casdon/modules/login/providers/login_pwd_provider.dart';
import 'package:casdon/modules/login/providers/login_wechat_provider.dart';
import 'package:casdon/modules/login/ui/screens/account_input_screen.dart';
import 'package:casdon/modules/login/ui/widgets/agreement_check.dart';
import 'package:casdon/modules/login/ui/widgets/social_login_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/modules/login/domain/usecases/check_account_usecase.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:keyboard_avoider/keyboard_avoider.dart';

@RoutePage()
class LoginPwdScreen extends ConsumerStatefulWidget {
  const LoginPwdScreen({super.key});

  @override
  ConsumerState<LoginPwdScreen> createState() => _LoginPwdScreenState();
}

class _LoginPwdScreenState extends ConsumerState<LoginPwdScreen> {
  final int gapSize = 24;
  late final TextEditingController _accountController;
  late final TextEditingController _pwdController;
  late final ProviderSubscription<LoginPwdState> _pwdSub;
  late final ProviderSubscription<LoginAppleState> _appleSub;
  late final ProviderSubscription<LoginWechatState> _wechatSub;

  @override
  void initState() {
    super.initState();
    final initialAccount = ref.read(loginTypeProvider) == LoginType.account
        ? ref.read(accountInputProvider)
        : '';
    _accountController = TextEditingController(text: initialAccount);
    _pwdController = TextEditingController();
    if (initialAccount.isNotEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          ref.read(loginPwdProvider.notifier).updateAccount(initialAccount);
        }
      });
    }
    _setupListeners();
  }

  void _setupListeners() {
    _pwdSub = ref.listenManual<LoginPwdState>(
      loginPwdProvider,
      (pri, next) => _handlePwdLoginState(pri, next),
    );

    _appleSub = ref.listenManual<LoginAppleState>(
      loginAppleProvider,
      (pri, next) => _handleLoginAppleState(pri, next),
    );

    _wechatSub = ref.listenManual<LoginWechatState>(
      loginWechatProvider,
      (pri, next) => _handleLoginWechatState(pri, next),
    );
  }

  @override
  void dispose() {
    _accountController.dispose();
    _pwdController.dispose();
    _pwdSub.close();
    _appleSub.close();
    _wechatSub.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(loginPwdProvider);
    final notifier = ref.read(loginPwdProvider.notifier);

    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        child: KeyboardAvoider(
          duration: const Duration(milliseconds: 300),
          autoScroll: true,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: gapSize.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: 48.h),
                SizedBox(height: 38.h),
                Image.asset(
                  'assets/images/logo_1.png',
                  width: 195.w,
                  height: 58.h,
                  fit: BoxFit.contain,
                ),
                SizedBox(height: 38.h),
                UnderlineTextField(
                  controller: _accountController,
                  hintText: "手机号或邮箱",
                  keyboardType: TextInputType.emailAddress,
                  onChanged: notifier.updateAccount,
                  validator: null,
                ),
                SizedBox(height: 8.h),
                UnderlineTextField(
                  controller: _pwdController,
                  obscureText: true,
                  hintText: "密码",
                  onChanged: notifier.updatePwd,
                ),
                SizedBox(height: 16.h),
                AgreementCheckBox(
                  value: state.agreed,
                  isRegister: true,
                  onChanged: (val) {
                    notifier.setAgree(val);
                    ref.read(loginAppleProvider.notifier).setAgree(val);
                    ref.read(loginWechatProvider.notifier).setAgree(val);
                  },
                ),
                SizedBox(height: 24.h),
                PrimaryButton(
                  text: '登录',
                  onPressed: () {
                    _pwdLogin(context, ref);
                  },
                  isLoading: state.status == CommonNetStatus.loading,
                ),
                _buildBottomActions(context, ref),
                SizedBox(height: 98.h),
                _buildSocialLoginSection(ref),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomActions(BuildContext context, WidgetRef ref) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        TextButton(
          onPressed: () => _regist(context, ref),
          child: Text(
            "新用户注册",
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor3,
            ),
          ),
        ),
        const Spacer(),
        TextButton(
          onPressed: () => _forgetPwd(context, ref),
          child: Text(
            "忘记密码",
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor3,
            ),
          ),
        ),
        const Spacer(),
        TextButton(
          onPressed: () {
            ref.read(loginTypeProvider.notifier).state = LoginType.optCode;
            context.router.maybePop();
          },
          child: Text(
            "验证码登录",
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor3,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSocialLoginSection(WidgetRef ref) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          child: Row(
            children: [
              Expanded(
                child: Divider(
                  thickness: 1,
                  color: Color(0xFFE0E0E0),
                  endIndent: 8.w,
                ),
              ),
              Text(
                '其他登录方式',
                style: TextStyle(color: Colors.grey, fontSize: 14.sp),
              ),
              Expanded(
                child: Divider(
                  thickness: 1,
                  color: Color(0xFFE0E0E0),
                  indent: 8.w,
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 20.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SocialLoginButton(
              iconAsset: 'assets/images/wechat_logo.png',
              onPressed: () {
                _wechatLogin(context, ref);
              },
            ),
            SizedBox(width: 40.w),
            SocialLoginButton(
              iconAsset: 'assets/images/apple_logo.png',
              onPressed: () {
                _appleLogin(context, ref);
              },
            ),
          ],
        ),
      ],
    );
  }

  void _forgetPwd(BuildContext context, WidgetRef ref) {
    ref.read(loginTypeProvider.notifier).state = LoginType.updatePwd;
    ForgetPwdRoute().push(context);
  }

  void _regist(BuildContext context, WidgetRef ref) {
    ref.read(loginTypeProvider.notifier).state = LoginType.register;
    RegisterAccountRoute().push(context);
  }

  void _handlePwdLoginState(LoginPwdState? pri, LoginPwdState next) {
    if (!mounted) return;

    switch (next.status) {
      case CommonNetStatus.success:
        ToastUtil.show(next.message ?? "登录成功");
        FocusScope.of(context).unfocus();
        context.router.replaceAll([const TabRoute()]);
        break;
      case CommonNetStatus.failure:
        ToastUtil.show(next.message ?? "登录失败");
        break;
      default:
        break;
    }
  }

  void _handleLoginAppleState(
    LoginAppleState? pri,
    LoginAppleState next,
  ) async {
    final notifier = ref.read(loginAppleProvider.notifier);
    if (next.status == CommonNetStatus.failure) {
      if (notifier.step == AppleLoginStep.login) {
        if (next.errorCode == "10012") {
          if (ref.context.mounted) {
            final ret = await showBindPhoneConfirmDialog(context);
            if ((ret ?? false) && mounted) {
              BindAccountRoute(source: "APPLE").push(context);
            } else {
              ref.read(loginWechatProvider.notifier).resetStateAndStep();
            }
          }
        }
      } else if (notifier.step == AppleLoginStep.auth) {
        ToastUtil.show(next.message ?? "登录失败");
      } else {
        ToastUtil.show(next.message ?? "登录失败");
      }
    } else if (next.status == CommonNetStatus.success &&
        (notifier.step == AppleLoginStep.login ||
            notifier.step == AppleLoginStep.afterbindingLogin)) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (context.mounted) context.router.replaceAll([const TabRoute()]);
        ;
      });
    }
  }

  void _handleLoginWechatState(
    LoginWechatState? pri,
    LoginWechatState next,
  ) async {
    final notifier = ref.read(loginWechatProvider.notifier);

    if (next.status == CommonNetStatus.failure) {
      if (notifier.step == WeChatLoginStep.login) {
        if (next.errorCode == "10012") {
          if (ref.context.mounted) {
            final ret = await showBindPhoneConfirmDialog(context);

            if ((ret ?? false) && mounted) {
              BindAccountRoute(source: "WECHAT_OPEN").push(context);
            } else {
              ref.read(loginWechatProvider.notifier).resetStateAndStep();
            }
          } else {
            ToastUtil.show(next.message ?? "登录失败");
          }
        }
      } else if (notifier.step == WeChatLoginStep.auth) {
        ToastUtil.show(next.message ?? "登录失败");
      }
    } else if (next.status == CommonNetStatus.success) {
      if (notifier.step == WeChatLoginStep.login ||
          notifier.step == WeChatLoginStep.afterbindingLogin) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (context.mounted) {
            context.router.replaceAll([const TabRoute()]);
          }
        });
      }
    }
  }

  void _wechatLogin(BuildContext context, WidgetRef ref) {
    _ensureAgreementAndRun(() {
      ref.read(loginTypeProvider.notifier).state = LoginType.wechat;
      ref.read(loginWechatProvider.notifier).auth();
    });
  }

  void _appleLogin(BuildContext context, WidgetRef ref) {
    _ensureAgreementAndRun(() {
      ref.read(loginTypeProvider.notifier).state = LoginType.apple;
      ref.read(loginAppleProvider.notifier).signIn();
    });
  }

  Future<void> _pwdLogin(BuildContext context, WidgetRef ref) async {
    final loginState = ref.read(loginPwdProvider);
    final account = loginState.account ?? _accountController.text;
    if (!loginState.agreed) {
      final ret = await _showAgreementDialog(context);
      if (ret == true) {
        ref.read(loginPwdProvider.notifier).setAgree(true);
        ref.read(loginAppleProvider.notifier).setAgree(true);
        ref.read(loginWechatProvider.notifier).setAgree(true);
        if (account.isNotEmpty) {
          ref.read(loginPwdProvider.notifier).updateAccount(account);
        }
        // 同意后继续走后续校验/登录流程
      } else {
        return;
      }
    }
    if (account.isEmpty) {
      ToastUtil.show("请输入账号");
      return;
    }
    final inputValidator = ref.watch(inputValidatorProvider);
    if (inputValidator.isValude(account) == false) {
      ToastUtil.show("账号格式不正确");
      return;
    }
    final checkAccountUsecase = ref.read(checkAccountUsecaseProvider);

    try {
      await checkAccountUsecase.execute(userName: account);
    } on BusinessException catch (e) {
      if (e.code == "10003") {
        ToastUtil.show("该账户未注册");
        return;
      } else {
        ToastUtil.show(e.msg);
      }
      rethrow;
    }

    ref.read(loginTypeProvider.notifier).state = LoginType.account;
    ref.read(loginPwdProvider.notifier).login();
  }

  Future<void> _ensureAgreementAndRun(FutureOr<void> Function() action) async {
    final agreed = ref.read(loginPwdProvider).agreed;
    if (!agreed) {
      final ret = await _showAgreementDialog(context);
      if (ret == true) {
        ref.read(loginPwdProvider.notifier).setAgree(true);
        ref.read(loginAppleProvider.notifier).setAgree(true);
        ref.read(loginWechatProvider.notifier).setAgree(true);
      } else {
        return;
      }
    }
    await action();
  }

  Future<bool?> _showAgreementDialog(BuildContext context) {
    return showAgreementDialog(context);
  }
}
